<?php
namespace app\model;

use think\Config;
use think\Cache;
use think\Session;

class Weixin
{
    function __construct() {
    }

    //微信获取基础access_token
    public function access_token(){
        Config::load(APP_PATH.'other.php');
        $config = Config::get('weixin');//获取微信配置
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['app_id'].'&secret='.$config['app_secret'];
        $access_token = http_curl($url);
        $access_token = json_decode($access_token);
        if(isset($access_token->errcode))return false;
        Cache::set('wx_access_token',$access_token->access_token,6800);//写入缓存中
        return $access_token->access_token;
    }

    //获取网页授权access_token
    public function auth_access_token($code){
        Config::load(APP_PATH.'other.php');
        $config = Config::get('weixin');//获取微信配置
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$config['app_id'].'&secret='.$config['app_secret'].'&code='.$code.'&grant_type=authorization_code';
        $access_token=[];
        if(empty(Session::get('name'))){
            $wx_access_token = http_curl($url);
            $access_token = json_decode($wx_access_token);
            if(isset($access_token->errcode))return false;
        }
        Session::set('name','thinkphp');
        return $access_token;
    }

    public function user_info($token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
        $wx_user_info = http_curl($url);
        $user_info = json_decode($wx_user_info);
        if(isset($user_info->errcode))return false;
        var_dump($user_info);
    }

    //自定义底部菜单创建
    public function create_menu($data=[],$access_token){
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $menu_status = http_curl($url,'POST',$data);
        if(isset($menu_status->errcode))return false;
        return true;
    }

    //网页授权获取code
    public function get_code($type=1){
        if($type==1){
            $scope = 'snsapi_userinfo';//详细授权(弹出确认页面)
        }else{
            $scope = 'snsapi_base';//只能获取到openid
        }
        Config::load(APP_PATH.'other.php');
        $config = Config::get('weixin');//获取微信配置
        $redirect_uri = urlEncode($config['redirect_uri']);
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config['app_id'].'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state=STATE#wechat_redirect';
        header("Location: ".$url);exit;
    }





}

